
public class BinaryTreeLevelConnector<T extends Comparable<T>> {

	public void connectLevels(BinTree<T> tree) {
		if (tree != null){
			connectSiblings(tree.theBTRootNode);
		}
	}

	private void connectSiblings(BNode<T> parent) {
		if (parent == null){
			return;
		}
		
		if (parent.leftBNode != null) {
			parent.leftBNode.sibling = parent.rightBNode;
		}

		connectCousins(parent);
		connectSiblings(parent.leftBNode);
		connectSiblings(parent.rightBNode);
		connectSiblings(parent.sibling);
	}
		
	private void connectCousins(BNode<T> parent) {
		if (parent.sibling == null){
			return;
		}
		
		BNode<T> cousin1 = getChild(parent);
		if (cousin1 != null){
			cousin1.sibling = getCousin(parent.sibling);
		}
	}

	private BNode<T> getCousin(BNode<T> parent) {
		if (parent == null){
			return null;
		}
		
		BNode<T> node = (parent.leftBNode == null) ? parent.rightBNode : parent.leftBNode;
		return node;
	}

	private BNode<T> getChild(BNode<T> parent) {
		if (parent == null){
			return null;
		}
		
		BNode<T> child = (parent.rightBNode == null) ? parent.leftBNode : parent.rightBNode;
		return child;
	}
}
